package com.loongtech.bi.action.admin;

import com.loongtech.bi.entity.system.EntitySysFunction;
import com.loongtech.bi.entity.system.EntitySysModel;
import com.loongtech.bi.entity.system.EntitySysUser;
import com.loongtech.bi.manager.system.SysFunctionManager;
import com.loongtech.bi.manager.system.SysModelManager;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.support.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 管理左边菜单权限
 * 
 * @author xckuang
 * @date 2014-10-08
 */
@Controller("leftAction")
@Scope("request")
public class LeftAction implements java.io.Serializable {
	private static final long serialVersionUID = 8L;
	@Autowired
	private Session session;
	@Autowired
	private SysUserManager sysUserManager;
	@Autowired
	private SysModelManager sysModelManager;
	@Autowired
	private SysFunctionManager sysFunctionManager;
	private Set<String> menuSet = new HashSet<>();
	private Set<String> pageSet = new HashSet<>();

	@Autowired
	public void init() {
		String username = session.getUserName();
		if (null == username || username.isEmpty()) {
			return;
		}
		EntitySysUser user = sysUserManager.getUserByName(username);
		if (null == user) {
			return;
		}
		
		menuSet.clear();
		pageSet.clear();

		if (user.getIsAdmin())
		{
			for (EntitySysModel module : sysModelManager.findAll()) {
				menuSet.add(module.getName());
			}
			for (EntitySysFunction function : sysFunctionManager.findAll()) {
				pageSet.add(function.getSrc());
			}
		} 
		else 
		{
			List<Object> list = sysModelManager.findByQuery("select f.src, m.name from EntitySysUserRole as ur, EntitySysRoleFunction as rf, EntitySysFunction as f,EntitySysModel as m where ur.roleId = rf.roleId and rf.functionId = f.id and f.modelId = m.id and ur.userId=:userId","userId",user.getId());
			if (null == list || list.isEmpty()) 
			{
				return;
			}
			for (Object o : list) 
			{
				Object[] ojbList = (Object[]) o;
				pageSet.add((String)ojbList[0]);
				menuSet.add((String)ojbList[1]);
			}
		}
	}

	public boolean allowModule(String menuName) 
	{
		return null != menuName && menuSet.contains(menuName);
	}

	public boolean allowItem(String pageName) 
	{
		return null != pageName && pageSet.contains(pageName);
	}
}